import React, { useRef } from 'react';
import Draggable from 'react-draggable';
import './Cursor.css';
import { setCurrentTime } from '@/store/timeline';
import { useDispatch, useSelector } from 'react-redux';
import { RootState } from '@/store';
import { eventBus } from '@/utils/eventBus';

interface CursorProps {
    position: number; // 游标位置（像素）
    isVisible?: boolean; // 是否显示游标
    onPositionChange?: (position: number) => void; // 位置变化回调
    minPosition?: number; // 最小位置
    maxPosition?: number; // 最大位置
}

const Cursor: React.FC<CursorProps> = ({ position, isVisible = true, onPositionChange, minPosition = 200, maxPosition = 3000 }) => {
    const dispatch = useDispatch();
    const pixelsPerSecond = useSelector((state: RootState) => state.timeline.pixelsPerSecond);
    const nodeRef = useRef<HTMLDivElement>(null);

    if (!isVisible) {
        return null;
    }

    const handleDragStart = () => {
        // 通知开始拖动
    };

    const handleDrag = (_e: any, data: any) => {
        const newPosition = Math.max(minPosition, Math.min(maxPosition, data.x));
        if (onPositionChange) {
            onPositionChange(newPosition);
        }
        // 设置当前播放时刻 时刻 = 游标位置 / 每秒像素数 单位毫秒
        dispatch(setCurrentTime(((newPosition - 200) / pixelsPerSecond) * 1000));
    };

    const handleDragStop = () => {
        // 通知拖动结束
    };

    return (
        <Draggable
            axis="x"
            position={{ x: position, y: 0 }}
            onDrag={handleDrag}
            onStart={handleDragStart}
            onStop={handleDragStop}
            bounds={{ left: minPosition, right: maxPosition }}
            handle=".timeline-cursor"
            nodeRef={nodeRef}
        >
            <div
                ref={nodeRef}
                className="timeline-cursor"
                style={{
                    cursor: 'ew-resize',
                }}
            />
        </Draggable>
    );
};

export default Cursor;
